﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
using System.Globalization;
using Cmd.TypeConverters;

namespace Cmd.TypeConverters
{
    internal static class TypeExtensions
    {
        internal static T FromString<T>(this string value)
        {
            ITypeConverter tc = TypeConverterHelpers.GetConverter<T>();

            if (tc == null)
            {
                throw new ApplicationException(string.Format("Cannot convert string to {0}! Consider adding a corresponding converter.", typeof(T)));
            }
            return (T)tc.ConvertFromString(value);
        }

        internal static object FromString(this string value, Type type)
        {
            if (type == typeof(string))
            {
                return value;
            }
            ITypeConverter tc = TypeConverterHelpers.GetConverter(type);

            if (tc == null)
            {
                throw new ApplicationException(string.Format("Cannot convert string to {0}! Consider adding a corresponding converter.", type));
            }
            return tc.ConvertFromString(value);
        }

        internal static string ToString<T>(this T value)
        {
            if (value == null)
            {
                return null;
            }
            ITypeConverter tc = TypeConverterHelpers.GetConverter<T>();

            if (tc == null)
            {
                throw new ApplicationException(string.Format("Cannot convert {0} to string! Consider adding a corresponding converter.", typeof(T)));
            }
            return tc.ConvertToString(value);
        }

        internal static string ToString(this object value, Type type)
        {
            if (value == null)
            {
                return null;
            }
            if (type == typeof(string))
            {
                return value as string;
            }
            ITypeConverter tc = TypeConverterHelpers.GetConverter(type);

            if (tc == null)
            {
                throw new ApplicationException(string.Format("Cannot convert {0} to string! Consider adding a corresponding converter.", type));
            }
            return tc.ConvertToString(value);
        }

        internal static bool IsCollection(this Type type)
        {
            return type.GetInterface("IList") != null ||
                type.GetInterface("ICollection") != null;
        }
    }
}
